package kubernetes

import (
	"golang.org/x/net/context"
	v1 "k8s.io/api/core/v1"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
)

var SvcWrap svcwrap = svcwrap{}

type svcwrap struct{}

func (svcwrap) List(namespace string) (*v1.ServiceList, error) {
	return clientset.CoreV1().Services(namespace).List(context.Background(), metav1.ListOptions{})
}

func (svcwrap) Get(namespace, name string) (*v1.Service, error) {
	return clientset.CoreV1().Services(namespace).Get(context.Background(), name, metav1.GetOptions{})
}

func (svcwrap) Delete(namespace, name string) error {
	return clientset.CoreV1().Services(namespace).Delete(context.Background(), name, metav1.DeleteOptions{})
}

// 这里只管理clusterip类型的svc
type svcAssemble struct {
	namespace    string
	name         string
	svctype      v1.ServiceType // ClusterIP
	servicePorts []v1.ServicePort
}

func NewSvcAssemble(namespace, name string, svctype v1.ServiceType) svcAssemble {
	return svcAssemble{namespace: namespace, name: name, svctype: svctype, servicePorts: []v1.ServicePort{}}
}

func NewSvcAssembleWithClusterIP(namespace, name string) svcAssemble {
	return svcAssemble{namespace: namespace, name: name, svctype: v1.ServiceTypeClusterIP, servicePorts: []v1.ServicePort{}}
}

func (sa svcAssemble) Port(name string, port int32) svcAssemble {
	sa.servicePorts = append(sa.servicePorts, v1.ServicePort{
		Name:        name,
		Port:        port,
		TargetPort:  intstr.IntOrString{Type: intstr.Int, IntVal: port},
	})
	return sa
}

func (sa svcAssemble) Create() (*v1.Service, error) {
	selector := map[string]string{"name": sa.name}
	s := &v1.Service{
		TypeMeta:   metav1.TypeMeta{Kind: "Service", APIVersion: "v1"},
		ObjectMeta: metav1.ObjectMeta{Namespace: sa.namespace, Name: sa.name, Labels: selector},
		Spec:       v1.ServiceSpec{Selector: selector, Type: sa.svctype, Ports: sa.servicePorts},
	}
	return clientset.CoreV1().Services(sa.namespace).Create(context.Background(), s, metav1.CreateOptions{})
}
